package com.zx.scp.service.impl;


import com.zx.map.utils.CommonResponseUtils;
import com.zx.map.utils.MyBeanUtils;
import com.zx.platform.utils.HttpClientCommon;
import com.zx.platform.utils.PmpUtils;
import com.zx.scp.service.IIncomeService;
import com.zx.scp.service.IncomHandleService;
import com.zx.scp.service.model.*;
import com.zx.scp.utils.PropertyUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by IntelliJ IDEA. User: Administrator Date: 15-6-7 Time: 上午1:12 To
 * change this template use File | Settings | File Templates.
 */
@Service
public class KubeiIncomeServiceImpl implements IIncomeService {
    /**
     * log
     */
    private static Logger log = Logger.getLogger(KubeiIncomeServiceImpl.class);
    @Autowired
    private IncomHandleService incomHandleService;

    /**
     * 装换对象
     * @param map
     * @param orderPayCallBackModel
     */
    private void transModel(Map map, OrderPayCallBackModel orderPayCallBackModel) {
        orderPayCallBackModel.setOrdId((String) map.get("p7"));
        BigDecimal money= new BigDecimal((String) map.get("p3")).divide(new BigDecimal("100")); // 对方返回金额单位为分 需要转成元
        orderPayCallBackModel.setPaymentAmt(money.doubleValue());
        orderPayCallBackModel.setPaymentId((String) map.get("p5"));
        orderPayCallBackModel.setPaymentTime((String) map.get("p2"));
        String transStatus=(String) map.get("c");
        orderPayCallBackModel.setTransStatus(transStatus.equals("0")?"S":"F");
    }

    /**
     * 按照key的字母顺序排序后的,返回的字符串
     *
     * @throws UnsupportedEncodingException
     */
    private Map<String, String> waitForSignatureString(
            Map<String, String> parameters) throws UnsupportedEncodingException {
        Map<String, String> map = new HashMap<String, String>();
        StringBuffer text = new StringBuffer("");
        StringBuffer param = new StringBuffer("");
        List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(
                parameters.entrySet());
        Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
            public int compare(Map.Entry<String, String> o1,
                               Map.Entry<String, String> o2) {
                return (o1.getKey()).toString().compareTo(o2.getKey());
            }
        });
        for (int i = 0; i < infoIds.size(); i++) {

            Map.Entry<String, String> tmpMap = infoIds.get(i);
            if (!("s".equalsIgnoreCase(tmpMap.getKey()) || "class"
                    .equalsIgnoreCase(tmpMap.getKey()))) {
                text.append(tmpMap.getValue());
                param.append(tmpMap.getKey()).append("=")
                        .append(URLEncoder.encode(tmpMap.getValue(), "UTF-8"));
                if (i < infoIds.size() - 1) {// 拼接param参数
                    param.append("&");
                } else {// 最后 拼接 末尾拼接partnerKey值
                    text.append(PropertyUtil.getValue("kubei_mer_key"));
                }
            }
        }
        map.put("sign", text.toString());
        map.put("param", param.toString());
        return map;
    }

    @Override
    public Map startPay(HttpServletRequest request, YintongPayRequestModel orderResponseDomain) throws Exception {
        log.info("支付请求参数:"
                + ToStringBuilder.reflectionToString(orderResponseDomain));
        CounectPay model = new CounectPay();
        model.setN(PropertyUtil.getValue("kubei_notify_url"));
        model.setP(PropertyUtil.getValue("kubei_mer_Id"));// partnerId
        model.setP0("");// 扩展属性 为空
        model.setP1(PropertyUtil.getValue("kubei_terminal_id"));// 机具号
        model.setP2(orderResponseDomain.getOrderId());// 交易号
        model.setP3(new BigDecimal(orderResponseDomain.getAmount()).multiply(new BigDecimal(100)).longValue()+"");// 金额
        model.setR(PmpUtils.getRandomString(4));// 随机字符串
        model.setT(Long.toString(System.currentTimeMillis()));// 时间戳
        Map<String, String> param = BeanUtils.describe(model);
        Map<String, String> sortMap = waitForSignatureString(param);
        String sign = PmpUtils.encoderByMD5(sortMap.get("sign").toString())
                .toUpperCase();
        model.setS(sign);//

        String requestUrl = PropertyUtil.getValue("kubei_pay_url")+ sortMap.get("param").toString() + "&s=" + sign;
        // 2.请求
        log.info("参数处理，支付请求接口方url信息：" + requestUrl);
        HttpClientCommon httpClientCommon = new HttpClientCommon();
        Map response = httpClientCommon.getResult(Map.class, requestUrl);
 //       Map response= MyBeanUtils.jsonToBean("{\"RESULT\":0,\"BODY\":\"http://a.counect.com/p/c.html?data=kaeUPflouT3fLKzyx9y8Tpg2W%2Bd%2B6FLW%2F%2BH1gr96vzIPJTWkZfDDcnbwS9dq8qByuI1%2FEmXz2v8kcD6GOuUJ3GXCy%2FD5rEzt\"}",Map.class);
        log.info("支付接口方返回信息:" + ToStringBuilder.reflectionToString(response));
        int result= (Integer) response.get("RESULT");
        if(0==result) {
            Map orderResult = new HashMap();
            orderResult.put("codeUrl", URLDecoder.decode((String) response.get("BODY"),"UTF-8"));
            //orderResult.put("codeImgUrl", response.get("code_img_url"));  //zxing 编码
            return CommonResponseUtils.successResponse(orderResult);
        } else {
            return CommonResponseUtils.failureResponse();
        }
    }

    @Override
    public Map winxinJsPay(HttpServletRequest request, YintongPayRequestModel orderResponseDomain) throws Exception {
        return startPay(request, orderResponseDomain);
    }

    @Override
    public Map payNotify(Map param)throws Exception {
        log.info("酷贝订单通知返回参数:" + MyBeanUtils.beanToJson(param));
        // 1、验签
        Map<String, String> sortMap = waitForSignatureString(param);
        String sign = PmpUtils.encoderByMD5(sortMap.get("sign").toString()).toUpperCase();
        String s= (String) param.get("s");
        boolean isSignValid=StringUtils.isNotBlank(s)&& s.equals(sign);
        if (isSignValid) {
            // 2、验签通过 业务处理
            log.debug("订单验签通过");
            OrderPayCallBackModel orderPayCallBackModel=new OrderPayCallBackModel();
            transModel(param,orderPayCallBackModel);
            incomHandleService.handleOrderCallBack(orderPayCallBackModel);
            return CommonResponseUtils.successResponse("success");
        } else {
            // 验证未通过
            log.error("异常订单,验签未通过，订单信息如下：" + ToStringBuilder.reflectionToString(param));
            return CommonResponseUtils.failureResponse("fail");
        }
    }
}
